package com.wetool.controller;

import java.security.Principal;
import java.util.List;
import javax.validation.Valid;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.wetool.common.commodity.CommodityResult;
import com.wetool.common.model.Message;
import com.wetool.exception.CategoryNameRepetitionException;
import com.wetool.exception.CategoryNotFindException;
import com.wetool.exception.DataRelationException;
import com.wetool.exception.MerchantNotLoginException;
import com.wetool.exception.NodeRelationException;
import com.wetool.exception.ParamCheckException;
import com.wetool.model.CategoryTree;
import com.wetool.service.commodity.CategoryService;
import com.wetool.model.CategoryAdd;
import com.wetool.model.CategoryModify;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

/**
 * 商品分类管理(商家库)控制器
 * @author lixin
 */
@RestController
@RequestMapping("/category")
@RefreshScope
@Api(description = "商品分类管理(商家库)")
public class CategoryController {
	
	private static final Logger logger = LogManager.getLogger(CategoryController.class); 

	@Autowired
	private CategoryService categoryService;

	@ApiOperation(value="商品分类列表(商家全部分类)", notes="已登录商家查询商品分类列表(商家全部分类)", response = Message.class)
	@ApiImplicitParam(name = "merchantId", value = "商家ID", required = true,paramType = "query", dataType = "Long")
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！"),
			@ApiResponse(code = 19,message = "商家未登录!")
	})
	@GetMapping("/tree")
	public ResponseEntity<?> getTree(Principal principal,Long merchantId) throws MerchantNotLoginException, CategoryNotFindException {
		logger.info("进入接口>商品分类列表(商家全部分类) . 参数：商家ID【{}】",merchantId);
		Long catagoryId = categoryService.getRootNode(-1L);
		List<CategoryTree> tree = categoryService.getTree(merchantId,catagoryId);
		logger.info("结束接口>商品分类列表(商家全部分类) ");
		return new ResponseEntity<Object>(new Message<>(CommodityResult.SUCCESS, tree), HttpStatus.OK); 
	}
	
	@ApiOperation(value="根据商品分类ID查询分类列表", notes="已登录的商家根据商品分类ID查询分类列表", response = Message.class)
	@ApiImplicitParams({
		@ApiImplicitParam(name = "categoryId", value = "商家ID", required = true,paramType = "path", dataType = "Long"),
		@ApiImplicitParam(name = "merchantId", value = "商家ID", required = true,paramType = "query", dataType = "Long")
    })
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！"),
			@ApiResponse(code = 19,message = "商家未登录!")
	})
	@RequestMapping(value = "/tree/{categoryId}" , method = RequestMethod.GET)
	public ResponseEntity<?> getTrees( Long merchantId,@PathVariable Long categoryId) throws MerchantNotLoginException, CategoryNotFindException {
		logger.info("进入接口>根据商品分类ID查询分类列表 . 参数：商家ID【{}】，商品分类ID【{}】",merchantId,categoryId); 
		List<CategoryTree> tree = categoryService.getTree(merchantId, categoryId);
		logger.info("结束接口>根据商品分类ID查询分类列表 "); 
		return new ResponseEntity<Object>(new Message<>(CommodityResult.SUCCESS, tree), HttpStatus.OK); 
	}

	@ApiOperation(value="添加商品分类目录", notes="已登录的商家添加商品分类目录", response = Message.class)
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！"),
			@ApiResponse(code = 6, message = "参数格式错误!")
	})
	@RequestMapping(method = RequestMethod.POST)
	public ResponseEntity<?> create(@Valid @RequestBody CategoryAdd categoryAdd,
			BindingResult bindingResult) throws ParamCheckException, MerchantNotLoginException, CategoryNameRepetitionException  {
		logger.info("进入接口>添加商品分类目录 . 参数：添加分类【{}】",categoryAdd); 
		if (bindingResult == null) {
			logger.debug("添加商品分类目录 参数格式不正确");
			throw new ParamCheckException(bindingResult);
		}
		categoryService.add(categoryAdd);
		logger.info("结束接口>添加商品分类目录 "); 
		return new ResponseEntity<Object>(new Message<>(CommodityResult.SUCCESS), HttpStatus.OK);
	}
	
	@ApiOperation(value="导入商品分类目录模板（商家注册调用接口）", notes="新增商家导入公共库模板商品分类目录", response = Message.class)
	@ApiImplicitParam(name = "merchantId", value = "商家ID", required = true,paramType = "path", dataType = "Long")
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！"),
			@ApiResponse(code = 19,message = "商家未登录!")
	})
	@RequestMapping(value = "/saveCategory/{merchantId}" ,method = RequestMethod.POST)
	public ResponseEntity<?> createCategoryByMerchant(@PathVariable Long merchantId) throws MerchantNotLoginException{
		logger.info("进入接口>导入商品分类目录模板（商家注册调用接口） . 参数：商家ID【{}】",merchantId); 
		categoryService.saveCategoryByMerchant(merchantId);
		logger.info("结束接口>导入商品分类目录模板（商家注册调用接口） "); 
		return new ResponseEntity<Object>(new Message<>(CommodityResult.SUCCESS), HttpStatus.OK);
	}

	@ApiOperation(value="修改商品分类目录", notes="已登录的商家修改商品分类目录", response = Message.class)
	@ApiImplicitParam(name = "categoryId", value = "商家ID", required = true,paramType = "path", dataType = "Long")
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！"),
			@ApiResponse(code = 4, message = "禁止修改目录类型！")
	})
	@RequestMapping(value = "/{categoryId}", method = RequestMethod.PATCH)
	public ResponseEntity<?> update(@PathVariable Long categoryId, @RequestBody CategoryModify categoryModify)
			throws Exception {
		logger.info("进入接口>修改商品分类目录 . 参数：商家库分类ID【{}】, 修改商品分类参数【{}】",categoryId,categoryModify); 
		categoryService.update(categoryId, categoryModify);
		logger.info("结束接口>修改商品分类目录"); 
		return new ResponseEntity<Object>(new Message<>(CommodityResult.SUCCESS), HttpStatus.OK);
	}

	@ApiOperation(value="删除商品分类列表", notes="已登录的商家删除商品分类列表", response = Message.class)
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！"),
			@ApiResponse(code = 2, message = "删除失败，该目录下存在商品数据!"),
			@ApiResponse(code = 3, message = "删除失败，该目录存在子节点！")
	})
	@RequestMapping(value = "/v2", method = RequestMethod.DELETE)
	public ResponseEntity<?> delete(@RequestBody List<Long> categoryId) throws NodeRelationException, DataRelationException {
		logger.info("进入接口>删除商品分类列表 . 参数：商家库分类ID【{}】",categoryId); 
		Message<?> message = categoryService.deletes(categoryId);
		logger.info("结束接口>删除商品分类列表");
		return ResponseEntity.ok(message);
	}
	
	@ApiOperation(value="删除商品分类列表", notes="已登录的商家删除商品分类列表", response = Message.class)
	@ApiImplicitParam(name = "categoryId", value = "商品分类ID", required = true,paramType = "path", dataType = "Long")
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！"),
			@ApiResponse(code = 2, message = "删除失败，该目录下存在商品数据!"),
			@ApiResponse(code = 3, message = "删除失败，该目录存在子节点！")
	})
	@RequestMapping(value = "/{categoryId}", method = RequestMethod.DELETE)
	public ResponseEntity<?> delete(@PathVariable Long categoryId) throws NodeRelationException, DataRelationException {
		logger.info("进入接口>删除商品分类列表 . 参数：商家库分类ID【{}】",categoryId); 
		com.wetool.common.model.Message<?> message = categoryService.delete(categoryId);
		logger.info("结束接口>删除商品分类列表");
		return ResponseEntity.ok(message);
	}
	
	@ApiOperation(value="提供进销存服务查询商品分类目录", notes="提供进销存服务查询商品分类目录", response = Message.class)
	@ApiImplicitParam(name = "categoryId", value = "商品分类ID", required = true,paramType = "path", dataType = "Long")
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！")
	})
	@RequestMapping(value = "/getByIdtree/{categoryId}" , method = RequestMethod.GET)
	public Long[] getByIdTrees(@PathVariable Long categoryId) throws MerchantNotLoginException {
		logger.info("进入接口>提供进销存服务查询商品分类目录 . 参数：商家库分类ID【{}】",categoryId); 
		if (categoryId == null) {
			categoryId = categoryService.getRootNode(-1L);
		}
		Long[] longs = categoryService.getIds(categoryId);
		logger.info("结束接口>提供进销存服务查询商品分类目录 "); 
		return longs; 
	}
}